package com.strongbj.iot.devices.amazonreader.request.listener;

import javax.jms.JMSException;
import javax.jms.Message;
import javax.jms.Session;
import javax.jms.TextMessage;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.jms.annotation.JmsListener;
import org.springframework.jms.listener.adapter.MessageListenerAdapter;
import org.springframework.stereotype.Component;

import com.alibaba.fastjson.JSON;
import com.google.gson.reflect.TypeToken;
import com.strongbj.core.message.MessageHandleContext;
import com.strongbj.iot.devices.amazonreader.request.handle.ActiveLabelHandle;
import com.strongbj.iot.devices.amazonreader.request.handle.CloseLabelHandle;
import com.strongbj.iot.devices.amazonreader.request.handle.InitiateBaseStationActiveUploadHandle;
import com.strongbj.iot.devices.amazonreader.request.message.MQBodyMessage;

/**
 * 接收MQ的消息并处理
 * @author yuzhantao
 *
 */
@Component
public class MQMessageOfReaderListener extends MessageListenerAdapter {
	private static Logger logger = LogManager.getLogger(MQMessageOfReaderListener.class.getName());
	// 通过策略模式处理不同的信息
	private MessageHandleContext<MQBodyMessage<Object>,Object> messageHandleContent;
	
	public MQMessageOfReaderListener(){
		super();
		this.messageHandleContent=new MessageHandleContext<>();
		// 添加消息处理类
		this.messageHandleContent.addHandleClass(new ActiveLabelHandle());
		this.messageHandleContent.addHandleClass(new CloseLabelHandle());
		this.messageHandleContent.addHandleClass(new InitiateBaseStationActiveUploadHandle());
	}
	
	@JmsListener(destination="serverReader",concurrency="1")
    public void onMessage(Message message, Session session) throws JMSException {
		if(message instanceof TextMessage){
			TextMessage tm = (TextMessage)message;
			String json = tm.getText();
			MQBodyMessage<Object> rm = JSON.parseObject(json,new TypeToken<MQBodyMessage<Object>>(){}.getType());
			this.messageHandleContent.handle(null,rm);
		}else{
			logger.info("无法解析的mq对象消息:"+message.getClass().getName());
		}
    }
}
